package cn.com.tarotframework.config.api;

import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springdoc.core.GroupedOpenApi;
import org.springdoc.core.SpringDocConfigProperties;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.List;

/**
 * copyright (C), 2022, 塔罗牌基础架构
 *
 * @program tarot-openapi-spring-boot-starter
 * @description OpenApi配置类
 * @author Jiang Xincan
 * @version 0.0.1
 * @create 2022/5/20 18:54
 **/
public class TarotOpenApiService {

    // 注入spring容器上下文
    private ApplicationContext applicationContext;

    // 注入自定义openapi配置参数
    private TarotOpenApiProperties tarotOpenApiProperties;


    public TarotOpenApiService() {}

    /**
     *  构造器注入本类属性参数
     * @param applicationContext spring上下文
     * @param tarotOpenApiProperties 自定义open配置参数类
     * @author xincan
     * @date 2023/1/12 16:07
     */
    public TarotOpenApiService(ApplicationContext applicationContext, TarotOpenApiProperties tarotOpenApiProperties) {
        this.applicationContext = applicationContext;
        this.tarotOpenApiProperties = tarotOpenApiProperties;
    }

    /**
     * 手动装载bean：将剩余api组中的数据组装成对象，交给spring容器处理
     * @author xincan
     * @date 2023/1/12 16:54
     */
    public void initOpenApi() {
        List<SpringDocConfigProperties.GroupConfig> groupConfigs = tarotOpenApiProperties.getGroup().getGroupConfigs();
        if(groupConfigs.size() > 1){
            ConfigurableApplicationContext context = (ConfigurableApplicationContext)applicationContext;
            DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory)context.getBeanFactory();
            for (int i = 1; i <groupConfigs.size(); i++) {
                GroupedOpenApi groupedOpenApi = GroupedOpenApi.builder()
                        .group(groupConfigs.get(i).getGroup())
                        .pathsToMatch(groupConfigs.get(i).getPathsToMatch().toArray(new String[0]))
                        .packagesToScan(groupConfigs.get(i).getPackagesToScan().toArray(new String[0]))
                        .build();
                defaultListableBeanFactory.registerSingleton(groupedOpenApi.getGroup(), groupedOpenApi);
            }
        }
    }


}
